﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using ExcelImportComponent;
using System.Text;
using Goodway.Dao.Utility;

namespace ExcelImport
{
    public partial class ExcelImportXml : System.Web.UI.Page
    {
        protected string DisplayHtml = "";

        private string importSessionId = "ExcelImportImport";

        private ExcelImporter import;

        public string id = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.btnUpload.Enabled = true;
                this.btnImport.Enabled = false;
                this.btnDownload.Enabled = true;
                id = Request["Id"];
                Session["Id"] = id;
            }
            else
            {
                if (Session[importSessionId] != null)
                {
                    import = (ExcelImporter)Session[importSessionId];
                    this.btnUpload.Enabled = !import.IsValid;
                    this.btnImport.Enabled = import.IsValid;
                }
            }
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            string fileName = this.FileUpload1.PostedFile.FileName;
            if (string.IsNullOrEmpty(fileName) || string.IsNullOrWhiteSpace(fileName) 
                || !Path.GetExtension(fileName).Equals(".xls"))
            {
                this.btnImport.Enabled = false;
                return;
            }
            fileName = Guid.NewGuid().ToString() + Path.GetFileName(fileName);
            string filePath = System.AppDomain.CurrentDomain.BaseDirectory + @"\ExcelImportTemplate\";
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            filePath = filePath + fileName;
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
            FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate);
            fs.Write(this.FileUpload1.FileBytes, 0, this.FileUpload1.FileBytes.Length);
            fs.Flush();
            fs.Close();
            this.import = new ExcelImporter(Session["Id"].ToString(), filePath);
            List<ExcelImportValidMessage> messages = import.DoValid();
            if (import.IsValid)
            {
                List<GoodwayEntity> entity = import.DoPreView();

                this.DisplayHtml = BuildPreMessage(import.GetPreViewList());
                this.btnUpload.Enabled = false;
                this.btnImport.Enabled = true;
            }
            else
            {
                this.DisplayHtml = BuildErrorMessage(messages);
                this.btnImport.Enabled = false;
                this.btnUpload.Enabled = true;

            }
            this.Session[importSessionId] = import;
            
        }

        private string BuildPreMessage(List<GoodwayEntity> entities)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("<table borderColor='black' class='JcTable_body' border=0 cellpadding=0 cellspacing=0 style='width:99%'>");
            if (entities.Count > 0)
            {
                GoodwayEntity firstEntity = entities[0];
                builder.Append("<tr>");
                foreach (string columnName in firstEntity.PropNames)
                {
                    builder.Append("<td class='JcTable_TitleTd'>");
                    builder.Append(columnName);
                    builder.Append("</th>");
                }
                builder.Append("</tr>");
                foreach (GoodwayEntity entity in entities)
                {
                    int index = entities.IndexOf(entity);
                    string strClass = "JcTable_Row1";
                    if (index % 2 == 0)
                    {
                        strClass = "JcTable_Row2";
                    }
                    builder.AppendFormat("<tr class='{0}'>", strClass);
                    foreach (string columnName in firstEntity.PropNames)
                    {
                        builder.Append("<td height='24'>");
                        builder.Append(string.IsNullOrEmpty(entity[columnName]) ? "&nbsp;" : entity[columnName]);
                        builder.Append("</td>");
                    }
                    builder.Append("<tr>");
                }
                builder.Append("</table>");
            }
            else
            {
                builder.Append("导入的EXCEL没有数据");
            }
            return builder.ToString();
        }

        private string BuildErrorMessage(List<ExcelImportValidMessage> messages)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("<table borderColor='black' class='JcTable_body' border=0 cellpadding=0 cellspacing=0 style='width:100%'><tr><td class='JcTable_TitleTd' style='width:20%'>错误列</th><td class='JcTable_TitleTd' style='width:20%'>值</th><td class='JcTable_TitleTd' style='width:60%'>错误描述</th></tr>");
            foreach (ExcelImportValidMessage message in messages)
            {
                int index = messages.IndexOf(message);
                for (int i = 0; i < message.ErrorMessage.Count; i++)
                {
                    string strClass = "JcTable_Row1";
                    if (index % 2 == 0)
                    {
                        strClass = "JcTable_Row2";
                    }
                    if (i == 0)
                    {
                        builder.AppendFormat("<tr class='{5}'><td height='24' rowspan='{2}'>{0}{1}</td><td rowspan='{2}'>{4}</td><td>{3}</td></tr>", message.Y, int.Parse(message.X) + import.StartRowCount + 1, message.ErrorMessage.Count, message.ErrorMessage[0], string.IsNullOrEmpty(message.Value) ? "&nbsp;" : message.Value, strClass);
                    }
                    else
                    {
                        builder.AppendFormat("<tr class='{1}'><td height='24'>{0}</td></tr>", message.ErrorMessage[i], strClass);
                    }
                }
            }
            builder.Append("</table>");
            return builder.ToString();
        }

        protected void btnImport_Click(object sender, EventArgs e)
        {
            ExcelImporter import = (ExcelImporter)this.Session[importSessionId];
            if (import.IsLive)
            {
                import.DoImport();
                
                DisplayHtml = "导入成功";

            }
            else
            {
                DisplayHtml = "不能重复导入";
            }

            this.btnImport.Enabled = false;
        }

        protected void btnDownload_Click(object sender, EventArgs e)
        {
            this.import = new ExcelImporter(Session["Id"].ToString(), string.Empty);
            string strFullName = string.Concat(AppDomain.CurrentDomain.BaseDirectory, @"\Template\" + this.import.Setting["TemplateName"]);

            Response.AddHeader("Content-Disposition", "attachment; filename=" + System.IO.Path.GetFileName(strFullName));
            Response.ContentType = "application/ms-xls";
            Response.ContentEncoding = System.Text.Encoding.Default;
            Response.WriteFile(strFullName);
            Response.End();
        }
    }
}
